package com.cdtu.handler;

import com.cdtu.NettyServer;
import com.cdtu.utils.NetUtils;
import com.cdtu.vo.ChannelHandlerContextVo;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;


/**
 * @author Mika
 * @date 2025/03/01 11:11
 * 显示客户端发的消息，并将连接添加到服务器中缓存
 **/
@Slf4j
public class DisplayMessageHandler extends SimpleChannelInboundHandler<ByteBuf> {
    private ChannelHandlerContextVo vo;

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
//        log.info("Display Message Handler");
//        ctx.fireChannelRead(msg);
    }

    @Override
    @Deprecated
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf buf) throws Exception {

        // 跳过没有数据
//        if (buf.readableBytes() <= 0) {
//            buf.release();
//            return;
//        }
//        // 对消息作拷贝
//        byte[] data = ByteBufUtil.getBytes(buf);
//
//        String hexString = Crc16Utils.byteTo16String(data);
//
//        log.info("接收到客户端 {}:{}-id-{} 发送的数据：\r\n{}",
//                vo.getHost(), vo.getPort(), vo.getClientIdToShort(), hexString);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ChannelHandlerContextVo vo = NetUtils.bindParams(ctx);
        this.vo = vo;
        // 存放连接
        NettyServer.channelGroup.add(ctx.channel());
        // 将连接存入服务器中
        NettyServer.channels.put(vo.getHost(), ctx.channel());
//        log.info("客户端 {}:{} 已连接服务器", vo.getHost(), vo.getPort());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {

//        log.info("客户端 {}:{} 已断线", vo.getHost(), vo.getPort());
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
//        cause.printStackTrace();
        ctx.close();
    }
}
